<template>
  <div class="table-main">
    <div class="query-content">
      <div class="query-search">
        <el-form :inline="true"
                 :model="formInline"
                 class="demo-form-inline">
          <el-form-item label="">
            <el-input 
                      v-model="formInline.condition"
                      placeholder="请输入主编单位、标准编号或标准名称"
                      style="min-width: 300px" />
          </el-form-item>
          <!-- <el-form-item label="标准类型:">
                <el-select
                  v-model="formInline.bzlx"
                  placeholder="请选择"
                  style="width: 240px"
                  clearable
                   
                >
                  <el-option label="全部" value="0" />
                  <el-option label="强制性标准" value="1" />
                  <el-option label="推荐性标准" value="2" />
                </el-select>
              </el-form-item> -->
          <el-form-item label="发布日期:">
            <el-date-picker v-model="formInline.date1"
                            type="daterange"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            clearable
                        />
          </el-form-item>
          <el-form-item label="实施日期:">
            <el-date-picker v-model="formInline.date2"
                            type="daterange"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            clearable
                            />
          </el-form-item>
        </el-form>
      </div>
      <div class="query-btn">
        <el-button 
                   type="primary"
                   @click="onSubmit">查询</el-button>
        <el-button 
                   type="success"
                   @click="onReset">重置</el-button>
      </div>
    </div>
    <el-table :data="tableData"
              border
              style="width: 100%"
             >
      <el-table-column prop="standardProjectName"
                       label="标准名称"
                       align="center" />
      <el-table-column prop="standardNumber"
                       label="标准编号"
                       align="center" />
      <el-table-column prop="editorUnitName"
                       label="主编单位"
                       align="center">
        <template #default="scope">
          <el-tooltip effect="dark"
                      :content="scope.row.editorUnitName"
                      placement="top"
                      :disabled="!scope.row.editorUnitName">
            <div class="editor-unit-text">
              {{ scope.row.editorUnitName }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="recordNumber"
                       label="备案号"
                       align="center" />
      <el-table-column prop="releaseTime"
                       label="发布日期"
                       align="center" />
      <el-table-column prop="implementationTime"
                       label="实施日期"
                       align="center" />
      <el-table-column prop=""
                       label="标准全文"
                       align="center">
        <template #default="scope">
          <el-tooltip effect="dark"
                      content="点击预览"
                      placement="bottom"
                      style="cursor: pointer;">
            <el-icon size="18"
                     @click="openwindow(scope.row)">
              <Document />
            </el-icon>
          </el-tooltip>
          &nbsp;&nbsp;&nbsp;
          <el-tooltip effect="dark"
                      content="点击下载"
                      placement="bottom"
                      style="cursor: pointer;">
            <el-icon size="18"
                     @click="downloadFile(scope.row)">
              <Download />
            </el-icon>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column        prop="abolishTime"
                       label="废止日期"
                       align="center">
                       <template #default="scope">
                         {{scope.row.abolishTime.substring(0, 10)}}
                       </template>

      </el-table-column>
    </el-table>
    <div class="pagination-content">
      <el-config-provider :locale="zhCn">
        <el-pagination v-model:current-page="currentPage"
                       v-model:page-size="pageSize"
                       :page-sizes="[10, 20, 30, 100]"
                       :small="small"
                       background
                       layout="sizes, prev, pager, next, jumper"
                       :total="total"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" />
      </el-config-provider>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted } from "vue";
  import CryptoJS from "crypto-js";
  
  import { ElConfigProvider, ElMessage } from "element-plus";
  import zhCn from "element-plus/es/locale/lang/zh-cn";
  import axios from "axios";
  import { formatDate } from "@/utils/dateFormat";
  import { useRouter } from "vue-router";
  import { getServerUrl } from '@/utils/url';
  const serverUrl = getServerUrl();
  const router = useRouter();

  const tableData = ref([]);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const formInline = reactive({
    condition: "",
    date1: [],
    date2: [],
    bzlx: "",
  });
  const small = ref(false);

  const onSubmit = () => {
      currentPage.value = 1;
    initData();
  };
  const onReset = () => {
    formInline.condition = "";
    formInline.date1 = [];
    formInline.date2 = [];
    currentPage.value = 1;
    formInline.bzlx = "";
    initData();
  };
  const handleSizeChange = (val: number) => {
    pageSize.value = val;
    initData();
  };
  const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    initData();
  };

  // const fileUrl = ref(':https://ciac.zjw.sh.gov.cn/'); // 文件URL
  const openwindow = async (value: any) => {
    const timestamp = Date.now();
    const secretKey = "jkysh2jgbstandard";
    // 生成receivedToken
    const receivedToken = CryptoJS.HmacSHA256(
      value.standardApprovalFileId + ":" + timestamp,
      secretKey
    ).toString(CryptoJS.enc.Hex);
    if (value.standardApprovalFileId) {
      try {
        const response = await axios.get(
          `${serverUrl}api/files/webPreview`,
          {
            params: {
              fileId: value.standardApprovalFileId,
              timestamp: timestamp,
              receivedToken: receivedToken,
            },
          }
        );

        if (!response.data.data) {
          ElMessage.error("文件不存在或数据无效");
        } else if (response.data.data.url) {
          window.open(response.data.data.url, "_blank");
        } else {
          ElMessage.error("文件预览失败: 未返回有效的预览URL");
        }
      } catch (error) {
        if (error.response) {
          const errorData = error.response.data;
          ElMessage.error(errorData.message || "文件预览失败");
        } else {
          ElMessage.error("网络异常，请稍后重试");
        }
      }
    }
  };
  const downloadFile = async (value: any) => {
    if (value.standardApprovalFileId) {
      const timestamp = Date.now();
      const secretKey = "jkysh2jgbstandard";
      // 生成receivedToken
      const receivedToken = CryptoJS.HmacSHA256(
        value.standardApprovalFileId + ":" + timestamp,
        secretKey
      ).toString(CryptoJS.enc.Hex);
      try {
        const response = await axios.get(
          serverUrl + "api/files/webDownload",
          {
            params: {
              // 修正：GET 请求参数应放在 `params` 中
              fileId: value.standardApprovalFileId,
              timestamp: timestamp,
              receivedToken: receivedToken,
            },

            responseType: "blob",
          }
        );


        

        // 从响应头中提取文件名和文件类型

        const contentDisposition =
          response.headers["content-disposition"] ||
          response.headers["Content-Disposition"];
        const contentType = response.headers["content-type"];

        // 默认文件名和文件类型
        let fileName =
          getFileNameFromContentDisposition(contentDisposition) ||
          "default-filename";
        let fileExtension = "bin"; // 默认扩展名

        // 提取文件名
        // if (contentDisposition) {
        //     const match = contentDisposition.match(/filename="?(.+)"?/);
        //     if (match && match[1]) {
        //         fileName = match[1];
        //     }
        // }

        // 提取文件扩展名（根据 Content-Type）
        if (contentType) {
          const extensionMap: Record<string, string> = {
            "application/pdf": "pdf",
            "application/msword": "doc",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
              "docx",
            "application/vnd.ms-excel": "xls",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
              "xlsx",
            "image/jpeg": "jpg",
            "image/png": "png",
            "text/plain": "txt",
          };
          fileExtension = extensionMap[contentType] || fileExtension;
        }

        // 确保文件名包含正确的扩展名
        if (!fileName.includes(".")) {
          fileName = `${fileName}.${fileExtension}`;
        }

        // 创建 Blob 对象并生成下载链接
        const blob = new Blob([response.data]);
        const downloadUrl = window.URL.createObjectURL(blob);

        // 创建 <a> 标签并触发下载
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = fileName; // 使用动态生成的文件名
        document.body.appendChild(a);
        a.click();

        // 清理资源
        document.body.removeChild(a);
        window.URL.revokeObjectURL(downloadUrl);
      } catch (error) {
        console.error("文件下载失败：", error);
      }
    } else {
      ElMessage.error("暂无文件");
    }
  };

  const getFileNameFromContentDisposition = (contentDisposition: string) => {
    if (!contentDisposition) return null;

    // 处理标准文件名（filename="..."）
    const filenameMatch = contentDisposition.match(/filename="?(.+?)"?(;|$)/i);
    if (filenameMatch && filenameMatch[1]) {
      return decodeURIComponent(filenameMatch[1]); // 解码 URL 编码
    }

    // 处理 RFC 5987 编码的文件名（filename*=UTF-8''...）
    const filenameStarMatch = contentDisposition.match(
      /filename\*=UTF-8''(.+?)(;|$)/i
    );
    if (filenameStarMatch && filenameStarMatch[1]) {
      return decodeURIComponent(filenameStarMatch[1]); // 解码 URL 编码
    }

    return null; // 未找到文件名
  };
  const initData = async () => {
    try {
      const publishStartDate = formInline.date1
        ? formatDate(formInline.date1[0], "yyyy-MM-dd HH:mm:ss")
        : "";
      const publishEndDate = formInline.date1
        ? formatDate(formInline.date1[1], "yyyy-MM-dd HH:mm:ss")
        : "";
      const implementStartDate = formInline.date2
        ? formatDate(formInline.date2[0], "yyyy-MM-dd HH:mm:ss")
        : "";
      const implementEndDate = formInline.date2
        ? formatDate(formInline.date2[1], "yyyy-MM-dd HH:mm:ss")
        : "";
      const response = await axios.post(
        serverUrl + "external/localStandard/list",
        {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          isAbolish: true,
          standardType: 0,
          condition: formInline.condition,
          publishStartDate: publishStartDate,
          publishEndDate: publishEndDate,
          implementStartDate: implementStartDate,
          implementEndDate: implementEndDate,
        }
      );
      const data = response.data.data.list.map((item: any) => ({
        ...item,
        releaseTime: item.releaseTime ? item.releaseTime.substring(0, 10) : "",
        implementationTime: item.implementationTime
          ? item.implementationTime.substring(0, 10)
          : "",
      }));
      tableData.value = data;
      total.value = response.data.data.total;
    } catch (error) {
      console.error("数据加载失败:", error);
    }
  };
  onMounted(() => {
    initData();
  });
  // 意见反馈
  const feedback = (value: any) => {
    router.push({ name: "standardQueryFeedback", params: { id: 123 } }); // 使用路由名称进行导航
  };
</script>
<style lang="scss" scoped>
.query-content {
  display: flex;
  justify-content: space-between;
}

.query-btn {
  min-width: 175px;
}

.pagination-content {
  margin-top: 1.43rem;
  display: flex;
  justify-content: center;
}

.icon-w {
  margin-left: 20px;
}

.editor-unit-text {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  white-space: normal;
  line-height: 1.5;
  max-height: 3;
}
</style>